<template>
    <el-row :gutter="15">
        <el-form :model="formData" :rules="rules" size="large" label-width="100px" ref="formRef"
            style="max-width: 450px;">
            <el-col :span="24" >
                <el-form-item label="城市" prop="city">
                    <el-select v-model="formData.city" placeholder="请选择城市" clearable :style="{ width: '100%' }" 
                    filterable style="width: 160px">
                        <el-option v-for="(item, index) in cityOptions" :key="index" :label="item"
                            :value="item"></el-option>  
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item size="large">
                    <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
                </el-form-item>
            </el-col>
        </el-form>
    </el-row>

</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
import { resetForm, showErrorMsg, showSuccessMsg, type ApiResponse } from '@/api/common';
import type { FormInstance, FormRules } from 'element-plus';
import { listAllCity, getCitySetting, citySetting } from '@/api/city/city';
import type { CitySettingRequest } from '@/api/city/city';
const getUserCitySetting = () => {
    getCitySetting().then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            if (res.data) {
                formData.city = res.data;
            }
        }
    })
}
getUserCitySetting();
const getAllCity = () => {
    listAllCity().then((res: ApiResponse<string[]>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            cityOptions.value= res.data;
        }
    })
}
getAllCity();
const formData = reactive<CitySettingRequest>({
    city: '',
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            citySetting(formData).then((res: ApiResponse<string>) => {
                if (res.status != 200) {
                    showErrorMsg(res.msg);
                } else {
                    showSuccessMsg("设置成功");
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 初始表单规则
let rules = ref<FormRules<CitySettingRequest>>({
    city: [{
        required: true,
        message: '请选择城市',
        trigger: 'change'
    }],
});

const formRef = ref<FormInstance>()
const cityOptions = ref<string[]>([])

</script>
<style scoped></style>